﻿from flask import Flask, g, render_template, request,flash,redirect,url_for,Blueprint
import pymysql,json,datetime
from .setting import *

menu_blue = Blueprint('menu',__name__)
def json_encoder(obj):
    if isinstance(obj, datetime.datetime):
        return obj.strftime("%Y-%m-%d %X")
    elif isinstance(obj, datetime.date):
        return obj.strftime("%Y-%m-%d")
@menu_blue.route('/sys/menu/list')
def menulist():
	# if request.args.get('menuName'):like = request.args.get('menuName')
	# else:like=''
	# if request.args.get('page'):page = request.args.get('page')
	# else:page=1
	# if request.args.get('limit'):limit = request.args.get('limit')
	# else:limit=10
	# print(like,page,limit)
	db = pymysql.connect(host=dbhost,user=dbuser,password=dbpassword,database=dbdatabase)
	cursor = db.cursor()
	# sql = "SELECT * from sys_menu  WHERE  name LIKE '%"+like+"%'  LIMIT "+str(limit) +" OFFSET " +str((int(page)-1)*int(limit))
	sql = "SELECT * from sys_menu "
	# sqlcount = "SELECT count(*) from sys_menu  WHERE  name LIKE '%"+like+"%'"
	sqlcount = "SELECT count(*) from sys_menu"
	if printsql:print(sql)
	try:
		cursor.execute(sql)
		dataList1 = cursor.fetchall()
		# for row in dataList1:
			# print(row)
		menu_idname_Dict={}
		for i in range(len(dataList1)):
			menu_idname_Dict[dataList1[i][0]]=dataList1[i][2]
		# print(menu_idname_Dict)
		dataList=[]
		for i in range(len(dataList1)):
			if dataList1[i][1] in menu_idname_Dict.keys():
				dataList.append({'menuId':dataList1[i][0],'parentId':dataList1[i][1],'name':dataList1[i][2],'url':dataList1[i][3],'perms':dataList1[i][4],'type':dataList1[i][5],'icon':dataList1[i][6],'orderNum':dataList1[i][7],'parentName':menu_idname_Dict[dataList1[i][1]],'list':None,'open':None})
			else:#root
				dataList.append({'menuId':dataList1[i][0],'parentId':dataList1[i][1],'name':dataList1[i][2],'url':dataList1[i][3],'perms':dataList1[i][4],'type':dataList1[i][5],'icon':dataList1[i][6],'orderNum':dataList1[i][7],'parentName':None,'list':None,'open':None})
				
			
		# print(dataList)
		cursor.execute(sqlcount)
		count = cursor.fetchall()[0][0]
		# print('count',count)
		# data={
				# 'msg': 'success',
				# 'code': 0,
				# 'page': {
					# 'totalCount': count,
					# 'pageSize': 10,
					# 'totalPage': 1,
					# 'currPage': 1,
					# 'list': dataList
					# }
				# }
		data=dataList
		return json.dumps(data,default=json_encoder)
	except Exception as e:
		return "Error: unable to fetch data from sys_menu"+str(e)
	db.close()
@menu_blue.route('/sys/menu/save',methods=['POST'])
def menusave():
	if request.data:
		d=json.loads(str(request.data, 'UTF-8'))
		# if 'menuId' in d.keys():menuId = d['menu_id']
		# else:menuId=''
		if 'parentId' in d.keys():parentId = d['parent_id']
		else:parentId=''
		if 'name' in d.keys():name = d['name']
		else:name=''
		if 'url' in d.keys():url = d['url']
		else:url=''
		if 'perms' in d.keys():perms = d['perms']
		else:perms=''
		if 'type' in d.keys():type = d['type']
		else:type=''
		if 'icon' in d.keys():icon = d['icon']
		else:icon=''
		if 'orderNum' in d.keys():orderNum = d['order_num']
		else:orderNum=''
	elif request.form:
		# menuId = request.form['menu_id']
		parentId = request.form['parent_id']
		name = request.form['name']
		url = request.form['url']
		perms = request.form['perms']
		type = request.form['type']
		icon = request.form['icon']
		orderNum = request.form['order_num']
	db = pymysql.connect(host=dbhost,user=dbuser,password=dbpassword,database=dbdatabase)
	cursor = db.cursor()
	sql = '''insert into sys_menu (parent_id,name,url,perms,type,icon,order_num) values('''+"'"+str(parentId)+"','"+str(name)+"','"+str(url)+"','"+str(perms)+"','"+str(type)+"','"+str(icon)+"','"+str(orderNum)+"')"
	if printsql:print(sql)
	try:
		cursor.execute(sql)
		db.commit()
	except Exception as e:
		db.rollback()
		return "Error: unable to save data from sys_user"+str(e)
	db.close()
	
	data={
      'msg': 'success',
      'code': 0
    }
	return json.dumps(data,default=json_encoder)
@menu_blue.route('/sys/menu/update',methods=['POST'])
def menuupdate():
	if request.data:
		d=json.loads(str(request.data, 'UTF-8'))
		if 'menuId' in d.keys():menuId = d['menu_id']
		else:menuId=''
		if 'parentId' in d.keys():parentId = d['parent_id']
		else:parentId=''
		if 'name' in d.keys():name = d['name']
		else:name=''
		if 'url' in d.keys():url = d['url']
		else:url=''
		if 'perms' in d.keys():perms = d['perms']
		else:perms=''
		if 'type' in d.keys():type = d['type']
		else:type=''
		if 'icon' in d.keys():icon = d['icon']
		else:icon=''
		if 'orderNum' in d.keys():orderNum = d['order_num']
		else:orderNum=''
	elif request.form:
		menuId = request.form['menu_id']
		parentId = request.form['parent_id']
		name = request.form['name']
		url = request.form['url']
		perms = request.form['perms']
		type = request.form['type']
		icon = request.form['icon']
		orderNum = request.form['order_num']
	db = pymysql.connect(host=dbhost,user=dbuser,password=dbpassword,database=dbdatabase)
	cursor = db.cursor()
	sql = "UPDATE sys_menu SET parent_id='"+str(parent_id)+"',name='"+str(name)+"',url='"+str(url)+"',perms='"+str(perms)+"',type='"+str(type)+"',icon='"+str(icon)+"',order_num='"+str(orderNum)+"'  WHERE menu_id = '"+str(menuId)+"'"
	if printsql:print(sql)
	try:
		cursor.execute(sql)
		db.commit()
	except Exception as e:
		db.rollback()
		return "Error: unable to delete data from sys_user"+str(e)
	db.close()

	data={
	  'msg': 'success',
	  'code': 0
	}
	return json.dumps(data,default=json_encoder)
@menu_blue.route('/sys/menu/delete',methods=['POST'])
def menudelete():
	if request.data:
		if printrequestdata:print(request.data)
		d=json.loads(str(request.data, 'UTF-8'))
		menuId = d['menuId']
	elif request.form:
		menuId = request.form['menuId']
	db = pymysql.connect(host=dbhost,user=dbuser,password=dbpassword,database=dbdatabase)
	cursor = db.cursor()
	sql = "DELETE FROM sys_menu WHERE menu_id = '"+str(menuId)+"'"
	if printsql:print(sql)
	try:
		cursor.execute(sql)
		db.commit()
	except Exception as e:
		db.rollback()
		# return "Error: unable to delete data from sys_user"+str(e)
		data={
		  'msg': 'fail'+str(e),
		  'code': 1
		}
		return json.dumps(data,default=json_encoder)
	finally:
		db.close()

	data={
	  'msg': 'success',
	  'code': 0
	}
	return json.dumps(data,default=json_encoder)
@menu_blue.route('/sys/menu/info')
@menu_blue.route('/sys/menu/info/<id>')
def info(id=None):
	db = pymysql.connect(host=dbhost,user=dbuser,password=dbpassword,database=dbdatabase)
	cursor = db.cursor()
	sql = "SELECT * from sys_menu where  user_id = '"+str(id)+"'"
	if printsql:print(sql)
	try:
		cursor.execute(sql)
		dataList1 = cursor.fetchall()
		# for row in dataList:
			# print(row)
		# print(dataList1)
		menu={'menuId':dataList1[0][0],'parentId':dataList1[0][1],'name':dataList1[0][2],'url':dataList1[0][3],'perms':dataList1[0][4],'type':dataList1[0][5],'icon':dataList1[0][6],'orderNum':dataList1[0][7]}
		data={
				'msg': 'success',
				'code': 0,
				'menu': menu
				}
		return json.dumps(data,default=json_encoder)
	except Exception as e:
		return "Error: unable to fetch data from sys_user"+str(e)
	db.close()
@menu_blue.route('/sys/menu/select')
def menuselect():
	db = pymysql.connect(host=dbhost,user=dbuser,password=dbpassword,database=dbdatabase)
	cursor = db.cursor()
	sql = "SELECT * from sys_menu"
	if printsql:print(sql)
	try:
		cursor.execute(sql)
		dataList1 = cursor.fetchall()
		# for row in dataList1:
			# print(row)
		dataList=[]
		for i in range(len(dataList1)):
			dataList.append({'menuId':dataList1[i][0],'parentId':dataList1[i][1],'name':dataList1[i][2],'url':dataList1[i][3],'perms':dataList1[i][4],'type':dataList1[i][5],'icon':dataList1[i][6],'orderNum':dataList1[i][7]})
		# print(dataList)
		# data={
				# 'msg': 'success',
				# 'code': 0,
				# 'list': dataList
				# }
		data=dataList
		return json.dumps(data,default=json_encoder)
	except Exception as e:
		return "Error: unable to fetch data from sys_menu"+str(e)
	db.close()
	
	
@menu_blue.route('/sys/menu/nav')
def menunav():
	db = pymysql.connect(host=dbhost,user=dbuser,password=dbpassword,database=dbdatabase)
	cursor = db.cursor()
	# sql = "SELECT * from sys_menu  WHERE  name LIKE '%"+like+"%'  LIMIT "+str(limit) +" OFFSET " +str((int(page)-1)*int(limit))
	sql = "SELECT * from sys_menu "
	if printsql:print(sql)
	try:
		cursor.execute(sql)
		dataList1 = cursor.fetchall()
		# for row in dataList1:
			# print(row)
		menu_idname_Dict={}
		for i in range(len(dataList1)):
			menu_idname_Dict[dataList1[i][0]]=dataList1[i][2]
		# print(menu_idname_Dict)
		dataList=[]
		for i in range(len(dataList1)):
			if dataList1[i][1] in menu_idname_Dict.keys():
				dataList.append({'menuId':dataList1[i][0],'parentId':dataList1[i][1],'name':dataList1[i][2],'url':dataList1[i][3],'perms':dataList1[i][4],'type':dataList1[i][5],'icon':dataList1[i][6],'orderNum':dataList1[i][7],'parentName':menu_idname_Dict[dataList1[i][1]],'list':None,'open':None})
			else:#root
				dataList.append({'menuId':dataList1[i][0],'parentId':dataList1[i][1],'name':dataList1[i][2],'url':dataList1[i][3],'perms':dataList1[i][4],'type':dataList1[i][5],'icon':dataList1[i][6],'orderNum':dataList1[i][7],'parentName':None,'list':None,'open':None})
				
		# print(dataList)
		menuList=[]
		for i in range(len(dataList)):
			if dataList[i]['parentId']==0:
				dataList[i]['list']=[]
				menuList.append(dataList[i])
		for i in range(len(menuList)):
			# print(menuList[i]['menuId'])
			# print(menuList[i]['parentId'])
			# print(menuList[i]['name'])
			for j in range(len(dataList)):
				if dataList[j]['parentId']==menuList[i]['menuId']:
					# print(dataList[j]['name'])
					menuList[i]['list'].append(dataList[j])
		# print(menuList)
	except Exception as e:
		return "Error: unable to fetch data from sys_menu"+str(e)
	db.close()
	
	permissions=[
		'sys:schedule:info',
		'sys:menu:update',
		'sys:menu:delete',
		'sys:config:info',
		'sys:menu:list',
		'sys:config:save',
		'sys:config:update',
		'sys:schedule:resume',
		'sys:user:delete',
		'sys:config:list',
		'sys:user:update',
		'sys:role:list',
		'sys:menu:info',
		'sys:menu:select',
		'sys:schedule:update',
		'sys:schedule:save',
		'sys:role:select',
		'sys:user:list',
		'sys:menu:save',
		'sys:role:save',
		'sys:schedule:log',
		'sys:role:info',
		'sys:schedule:delete',
		'sys:role:update',
		'sys:schedule:list',
		'sys:user:info',
		'sys:schedule:run',
		'sys:config:delete',
		'sys:role:delete',
		'sys:user:save',
		'sys:schedule:pause',
		'sys:log:list',
		'sys:oss:all'
	  ]
	return json.dumps({'code':0,'menuList':menuList,'permissions':permissions},default=json_encoder)
	